const { connection } = require('./index');

exports.getPostInfoById = (id) => {
  return new Promise(function (resolve, reject) {
    connection.query(
      `SELECT * FROM post WHERE post_id='${id}'`,
      function (err, result) {
        if (err) {
          reject({ message: 'Internal server error.' });
        }
        resolve(result);
      }
    );
  });
};

exports.addPost = (info) => {
  const { post_author, post_text, post_id } = info;
  const _now_time = new Date();
  const sqlParams = [post_id, post_author, post_text, _now_time, _now_time];

  return new Promise(function (resolve, reject) {
    connection.query(
      'INSERT INTO post(post_id, post_author, post_text, create_time, last_modified) VALUES(?,?,?,?,?)',
      sqlParams,
      function (err, result) {
        if (err) {
          reject({ message: 'Internal server error.' });
        }
        resolve(result);
      }
    );
  });
};

exports.setPostText = (info) => {
  const { post_id, post_text } = info;
  const _now_time = new Date();
  const sqlParams = [post_text, _now_time, post_id];

  return new Promise(function (resolve, reject) {
    connection.query(
      'UPDATE post SET post_text=?, last_modified=? WHERE post_id=?',
      sqlParams,
      function (err, result) {
        if (err) {
          reject({ message: 'Internal server error.' });
        }
        resolve(result);
      }
    );
  });
};

exports.deletePostById = (id) => {
  return new Promise(function (resolve, reject) {
    connection.query(
      `DELETE FROM post where post_id='${id}'`,
      function (err, result) {
        if (err) {
          reject({ message: 'Internal server error.' });
        }
        resolve(result);
      }
    );
  });
};

exports.getNearestPostByAuthor = (info) => {
  const { authors, current_page, page_size } = info;
  _selstr = "post_author='" + authors[0] + "'";
  for (let i = 1; i < authors.length; i++) {
    _str = "post_author='" + authors[i] + "'";
    _selstr = _selstr + ' OR ' + _str;
  }

  return new Promise(function (resolve, reject) {
    connection.query(
      'SELECT * FROM post WHERE ' +
        _selstr +
        ' ORDER BY create_time DESC LIMIT ' +
        (current_page - 1) * page_size +
        ',' +
        page_size,
      function (err, result) {
        if (err) {
          reject(err.message);
        }
        resolve(result);
      }
    );
  });
};

exports.getNearestPost = (info) => {
  const { current_page, page_size } = info;
  return new Promise(function (resolve, reject) {
    connection.query(
      'SELECT * FROM post ORDER BY create_time DESC LIMIT ' +
        (current_page - 1) * page_size +
        ',' +
        page_size,
      function (err, result) {
        if (err) {
          reject({ message: 'Internal server error.' });
        }
        resolve(result);
      }
    );
  });
};
